import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

import { IS_PUBLIC_KEY } from '../constants/auth.constant';
import { TreadstoneService } from '../services/treadstone.service';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private readonly treadstone: TreadstoneService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const { path, user } = context.switchToHttp().getRequest();
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }
    if (!user) {
      return false;
    }
    const granted = await this.treadstone.checkApiPermissions({ path: path.slice(4), userId: user.serial });
    if (!granted) {
      throw new ForbiddenException('你没有权限访问该资源，请联系管理员');
    }
    return true;
  }
}
